// 文件上传API模块
import express from 'express';
import UploadService from '../../config/Upload.js';
import { authMiddleware } from '../../middleware/authMiddleware.js';
import { asyncHandler, ApiError } from '../../middleware/errorHandler.js';
import path from 'path';

const router = express.Router();
const chunkManager = UploadService.getChunkManager();

// 通用上传响应处理程序
const handleUploadResponse = (req, res) => {
  if (!req.files || req.files.length === 0) {
    throw new ApiError(400, '没有上传文件');
  }
  
  const files = req.files.map(file => ({
    fileName: file.filename,
    originalName: file.originalname,
    size: file.size,
    mimeType: file.mimetype,
    url: `/${file.destination}/${file.filename}`
  }));
  
  return res.json({
    success: true,
    message: '文件上传成功',
    data: files.length === 1 ? files[0] : files
  });
};

// 图片上传接口
router.post('/image', authMiddleware, asyncHandler(async (req, res, next) => {
  UploadService.imageUploader(req, res, (err) => {
    if (err) {
      return next(err instanceof ApiError ? err : new ApiError(400, `上传失败: ${err.message}`));
    }
    handleUploadResponse(req, res);
  });
}));

// 文档上传接口
router.post('/document', authMiddleware, asyncHandler(async (req, res, next) => {
  UploadService.documentUploader(req, res, (err) => {
    if (err) {
      return next(err instanceof ApiError ? err : new ApiError(400, `上传失败: ${err.message}`));
    }
    handleUploadResponse(req, res);
  });
}));

// 视频上传接口
router.post('/video', authMiddleware, asyncHandler(async (req, res, next) => {
  UploadService.videoUploader(req, res, (err) => {
    if (err) {
      return next(err instanceof ApiError ? err : new ApiError(400, `上传失败: ${err.message}`));
    }
    handleUploadResponse(req, res);
  });
}));

// 音频上传接口
router.post('/audio', authMiddleware, asyncHandler(async (req, res, next) => {
  UploadService.audioUploader(req, res, (err) => {
    if (err) {
      return next(err instanceof ApiError ? err : new ApiError(400, `上传失败: ${err.message}`));
    }
    handleUploadResponse(req, res);
  });
}));

// 通用文件上传接口
router.post('/general', authMiddleware, asyncHandler(async (req, res, next) => {
  UploadService.generalUploader(req, res, (err) => {
    if (err) {
      return next(err instanceof ApiError ? err : new ApiError(400, `上传失败: ${err.message}`));
    }
    handleUploadResponse(req, res);
  });
}));

// ===== 分块上传相关路由 =====

// 初始化分块上传会话
router.post('/chunk/init', authMiddleware, asyncHandler(async (req, res) => {
  const { fileName, fileSize, totalChunks } = req.body;
  
  if (!fileName || !fileSize || !totalChunks) {
    throw new ApiError(400, '缺少必要的文件信息');
  }
  
  const sessionId = chunkManager.initSession({
    fileName,
    fileSize,
    totalChunks: parseInt(totalChunks)
  });
  
  return res.json({
    success: true,
    message: '分块上传会话已初始化',
    data: { sessionId }
  });
}));

// 上传分块
router.post('/chunk/upload', authMiddleware, asyncHandler(async (req, res, next) => {
  UploadService.chunkUploader(req, res, async (err) => {
    if (err) {
      return next(err instanceof ApiError ? err : new ApiError(400, `分块上传失败: ${err.message}`));
    }
    
    if (!req.file) {
      return next(new ApiError(400, '没有文件数据'));
    }
    
    const { sessionId, chunkIndex } = req.body;
    
    if (!sessionId || chunkIndex === undefined) {
      return next(new ApiError(400, '缺少会话ID或分块索引'));
    }
    
    try {
      const result = chunkManager.handleChunk(
        sessionId,
        parseInt(chunkIndex),
        req.file
      );
      
      return res.json({
        success: true,
        message: '分块上传成功',
        data: result
      });
    } catch (error) {
      return next(error instanceof ApiError ? error : new ApiError(500, `处理分块失败: ${error.message}`));
    }
  });
}));

// 完成分块上传并合并文件
router.post('/chunk/complete', authMiddleware, asyncHandler(async (req, res) => {
  const { sessionId, targetDir } = req.body;
  
  if (!sessionId) {
    throw new ApiError(400, '缺少会话ID');
  }
  
  const result = await chunkManager.mergeChunks(sessionId, targetDir);
  
  return res.json({
    success: true,
    message: '文件合并完成',
    data: result
  });
}));

// 取消分块上传
router.post('/chunk/cancel', authMiddleware, asyncHandler(async (req, res) => {
  const { sessionId } = req.body;
  
  if (!sessionId) {
    throw new ApiError(400, '缺少会话ID');
  }
  
  chunkManager.cleanupSession(sessionId);
  
  return res.json({
    success: true,
    message: '上传已取消'
  });
}));

export default router; 